const { Sequelize, DataTypes } = require('sequelize')
const sequelize = require('../config/database')
const logger = require('../utils/logger')

// 导入模型
const models = {
  User: require('./User')(sequelize),
  File: require('./File')(sequelize),
  Product: require('./Product')(sequelize),
  Order: require('./Order')(sequelize),
  OrderItem: require('./OrderItem')(sequelize),
  PointsTransaction: require('./PointsTransaction')(sequelize),
  Invitation: require('./Invitation')(sequelize),
  ShareStatistics: require('./ShareStatistics')(sequelize),
  MemberLevel: require('./MemberLevel')(sequelize),
  MemberUpgrade: require('./MemberUpgrade')(sequelize),
  PrintConfig: require('./PrintConfig')(sequelize),
  PrintReservation: require('./PrintReservation')(sequelize),
  AdView: require('./AdView')(sequelize),
  Ad: require('./Ad')(sequelize),
  Role: require('./Role')(sequelize),
  Permission: require('./Permission')(sequelize),
  Admin: require('./Admin')(sequelize),
  AdminRole: require('./AdminRole')(sequelize),
  RolePermission: require('./RolePermission')(sequelize),
  Message: require('./Message')(sequelize),
  NotificationLog: require('./NotificationLog')(sequelize)
}

// 建立模型之间的关联关系
Object.keys(models).forEach((modelName) => {
  if (models[modelName].associate) {
    models[modelName].associate(models)
  }
})

// 注意：User和Order的关联关系已经在各自的模型文件中定义了，这里不需要重复定义

// 设置管理员权限系统关联关系
const { Admin, Role, Permission, AdminRole, RolePermission } = models

// 管理员和角色的多对多关系
Admin.belongsToMany(Role, {
  through: AdminRole,
  foreignKey: 'adminId',
  otherKey: 'roleId',
  as: 'roles'
})

Role.belongsToMany(Admin, {
  through: AdminRole,
  foreignKey: 'roleId',
  otherKey: 'adminId',
  as: 'admins'
})

// 角色和权限的多对多关系
Role.belongsToMany(Permission, {
  through: RolePermission,
  foreignKey: 'roleId',
  otherKey: 'permissionId',
  as: 'permissions'
})

Permission.belongsToMany(Role, {
  through: RolePermission,
  foreignKey: 'permissionId',
  otherKey: 'roleId',
  as: 'roles'
})

// AdminRole 关联
AdminRole.belongsTo(Admin, { foreignKey: 'adminId', as: 'admin' })
AdminRole.belongsTo(Role, { foreignKey: 'roleId', as: 'role' })
AdminRole.belongsTo(Admin, { foreignKey: 'assignedBy', as: 'assigner' })

// RolePermission 关联
RolePermission.belongsTo(Role, { foreignKey: 'roleId', as: 'role' })
RolePermission.belongsTo(Permission, { foreignKey: 'permissionId', as: 'permission' })
RolePermission.belongsTo(Admin, { foreignKey: 'assignedBy', as: 'assigner' })

// 导出模型和Sequelize实例
module.exports = {
  ...models,
  sequelize,
  Sequelize,
  DataTypes
}